﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KPIS.GERP.Models; 
using System.Data.Entity;
using System.IO;
using System.Text;
using KPIS.GERP.Models.SYS;
using OfficeOpenXml;
using OfficeOpenXml.Style;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    public class AbsenceAdminFilter
    {
        public AbsenceAdminFilter()
        {
            this.Month = DateTime.Now.Month;
            this.Year = Convert.ToInt32(DateTime.Now.ToString("yyyy"));
        }

        public int Month { get; set; }
        public int Year { get; set; }

        public List<string> GetRecordStatusFiltered()
        {
            List<string> s = new List<string>();
            if (chbW) s.Add("W");
            if (chbJ) s.Add("J");
            if (chbU) s.Add("U");
            if (chbA) s.Add("A");
            if (chbR) s.Add("R");
            if (chbP) s.Add("P");
            if (chbC) s.Add("C");
            return s;
        }

        public bool chbW { get; set; }
        public bool chbJ { get; set; }
        public bool chbU { get; set; }
        public bool chbA { get; set; }
        public bool chbR { get; set; }
        public bool chbP { get; set; }
        public bool chbC { get; set; }
    }

    public class AbsencQuotaFilter
    {
        public AbsencQuotaFilter()
        {
            this.StartDate = DateTime.Now.Date;
            this.EndDate = DateTime.Now.Date;
        } 

        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; } 
    }

    public class AbsenceAdminController : Controller
    {
        public ActionResult Index()
        {
            return View(new AbsenceAdminFilter());
        }

        public ActionResult _IndexGrid(AbsenceAdminFilter model = null)
        {
            if (model == null)
            {
                model = new AbsenceAdminFilter();
            }
            return View(model);
        }

        public static string GetThaiText(string recordStatusCode)
        {
            string recordStatusName;
            switch (recordStatusCode)
            {
                case "W":
                    recordStatusName = "ยังไม่ส่งขออนุมัติ";
                    break;
                case "J":
                    recordStatusName = "ไม่ผ่านการอนุมัติ";
                    break;
                case "U":
                    recordStatusName = "ใช้งานอยู่";
                    break;
                case "A":
                    recordStatusName = "อนุมัติแล้ว";
                    break;
                case "R":
                    recordStatusName = "ถูกส่งกลับให้แก้ไข";
                    break;
                case "P":
                    recordStatusName = "รออนุมัติ";
                    break;
                case "C":
                    recordStatusName = "ยกเลิก";
                    break;
                case "D":
                    recordStatusName = "ลบ";
                    break;
                default:
                    recordStatusName = recordStatusCode;
                    break;
            }
            return recordStatusName;
        }

        public ActionResult Details(int id)
        {
            var model = new GERPContext().PsAbsences
                .Include(o => o.Employee)
                .Include(o => o.AbsenceType)
                .FirstOrDefault(o => o.AbsenceId == id);
            return View(model);
        }

        public ActionResult AbsenceQuotaUsed(AbsencQuotaFilter model = null)
        {
            if (model == null)
            {
                model = new AbsencQuotaFilter();
            }
            return View(model);
        }

        public ActionResult AbsenceQuotaUsedExcel(AbsencQuotaFilter model = null)
        {
            string fileDownloadName = @"C:\temp\" + DateTime.Now.ToDbFormat() +".xlsx"; 
            var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

            ExcelPackage package = new ExcelPackage();
            var ws = package.Workbook.Worksheets.Add("Sample1");

            ws.Cells[1,1].Value = "แสดงข้อมูลโควต้าการลารายบุคคล " + model.StartDate.ToShortDateString() + " - " + model.EndDate.ToShortDateString();
            ws.Cells[1, 1].Style.Font.Bold = true;
            ws.Cells[1, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;

            ws.Cells[2,1].Value = "เจ้าหน้าที่";
            ws.Cells["A2:A3"].Merge = true;
            ws.Column(1).Width = 37;
            ws.Row(2).Height = 27;

            var context = new GERPContext(true);
            var employees = context.Employees
                .Include(o => o.MasNamePrefix)
                .Include(o => o.MasEmployeeType)
                .Include(o => o.Position)
                .Include(o => o.MasEmployeeStatus)
                .Where(o => o.RecordStatus != "D" && o.MasEmployeeStatus.Active == "1")
                .OrderBy(o => o.EmpTypeId)
                .ThenBy(o => o.Position.PosNo);
            var absencesInCriteria = (context.PsAbsences
                .Include(o => o.AbsenceType)
                .Where(o => o.RecordStatus != "D" 
                && model.StartDate >= o.StartDate && o.StartDate <= model.EndDate)).ToList();
            var absenceRules = context.RuleAbsences.Include(o => o.AbsenceType).Where(o => o.RecordStatus != "D").ToList();

            var absenceType = context.PsAbsenceTypes.Where(o => o.RecordStatus != RecordStatus.DeletedStatus).ToList();

            int type = 0;
            foreach (var at in absenceType)
            {
                int col = 2 + (type++*2);
                string s = at.AbsenceTypeName;
                    
                var absenceRule1 = absenceRules.FirstOrDefault(o => o.AbsenceTypeId == at.AbsenceTypeId);
                if (absenceRule1 != null)
                {
                    s += "(" + ((absenceRule1.DayLimit ?? 0).ToString("#,##0.#")) + " วัน)";
                }
                ws.Cells[2, col].Value = s;
                ws.Cells[2, col].Style.WrapText = true;
                ws.Cells[3, col].Value = "ใช้ไป";
                ws.Cells[3, col+1].Value = "คงเหลือ";
            }

            int empIndex = 0;
            foreach (var e in employees)
            {
                int row = (empIndex++) + 4;
                var absenceOfEmpInCriteria = absencesInCriteria.Where(o => o.EmpId == e.EmpId);
                ws.Cells[row, 1].Value = e.Position.PosNo + " - " + @e.FullName;

                int type2 = 0;
                foreach (var at in absenceType)
                {
                    int col = 2 + (type2++*2);
                    var absenceRule = absenceRules.FirstOrDefault(o => o.AbsenceTypeId == at.AbsenceTypeId);
                    decimal dayUsedInYear = 0;
                    decimal dayUsedInMonth = 0;
                    var absOfTypeInYear = absenceOfEmpInCriteria.Where(o => o.AbsenceTypeId == at.AbsenceTypeId);
                    var absOfTypeInMonth = absenceOfEmpInCriteria.Where(o => o.AbsenceTypeId == at.AbsenceTypeId);
                    foreach (var ab in absOfTypeInYear)
                    {
                        dayUsedInYear += ab.DayCount ?? 0;
                    }

                    foreach (var ab in absOfTypeInMonth)
                    {
                        dayUsedInMonth += ab.DayCount ?? 0;
                    }
                    // < td >
                    if (dayUsedInMonth == 0)
                    {
                        ws.Cells[row, col].Value = (dayUsedInMonth.ToString("#,##0.#"));
                        ws.Cells[row, col].Style.Font.Color.SetColor(System.Drawing.Color.DarkGray);
                    }
                    else
                    {
                        ws.Cells[row, col].Value = (dayUsedInMonth.ToString("#,##0.#"));

                    }

                    // </ td >
                    // < td > 
                    var dayLeft = (((absenceRule == null ? 0 : absenceRule.DayLimit) - dayUsedInYear) ?? 0);


                    if (dayLeft == (absenceRule == null ? 0 : absenceRule.DayLimit))
                    {
                        ws.Cells[row, col + 1].Value = (dayLeft.ToString("#,##0.#"));
                        ws.Cells[row, col + 1].Style.Font.Color.SetColor(System.Drawing.Color.DarkGray);
                    }
                    else
                    {
                        ws.Cells[row, col + 1].Value = (dayLeft.ToString("#,##0.#"));
                    }
                    // </ td >
                }
            }
            var fileStream = new MemoryStream();
            package.SaveAs(fileStream);
            fileStream.Position = 0;

            var fsr = new FileStreamResult(fileStream, contentType);
            fsr.FileDownloadName = fileDownloadName;

            return fsr;

        }
    }
}